/**
 * 
 */
package jvs.core.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Scanner;

/**
 * @author qiangli
 *
 */
public class Utils {

	/**
	 * 
	 */
	private Utils() {
	}

	public static void parseUri(List<NVPair> result, String query,
			final String encoding) {
		if (query != null && query.length() > 0) {
			int idx = query.indexOf("?");
			if (idx > 0) {
				query = query.substring(idx + 1);
				parse(result, new Scanner(query), encoding);
			}
		}
	}

	public static void parseContent(List<NVPair> result,
			final byte[] content, String encoding) throws IOException {
		if (content != null && content.length > 0) {
			parse(result, new Scanner(new String(content, encoding)),
					encoding);
		}
	}

	public static void parse(final List<NVPair> result,
			final Scanner scanner, final String encoding) {
		scanner.useDelimiter("&");
		while (scanner.hasNext()) {
			final String[] nameValue = scanner.next().split("=");
			if (nameValue.length == 0 || nameValue.length > 2) {
				throw new IllegalArgumentException("bad parameter");
			}
			final String name = decode(nameValue[0], encoding);
			String value = null;
			if (nameValue.length == 2) {
				value = decode(nameValue[1], encoding);
			}
			result.add(new NVPair(name, value));
		}
	}

	public static String decode(final String content, final String encoding) {
		try {
			return URLDecoder.decode(content, encoding != null ? encoding
					: "ISO-8859-1");
		} catch (UnsupportedEncodingException problem) {
			throw new IllegalArgumentException(problem);
		}
	}
	
	public static String parseJid(String uri) {
		if (uri == null) {
			return null;
		}
		if (uri.startsWith("v:") || uri.startsWith("V:")) {
			uri = uri.substring(2);
		}
		if (!uri.startsWith("/~")) {
			return null;
		}
		String jid = null;
		int idx = uri.indexOf("/", 2);
		if (idx > 0) {
			jid = uri.substring(2, idx);
		} else {
			jid = uri.substring(2);
		}
		return jid;
	}
	
	/**
	 * @param uri format: /~<peer>/path
	 * @return path component after the peer id
	 */
	public static String parsePath(String uri) {
		if (uri == null) {
			return uri;
		}
		if (uri.startsWith("v:") || uri.startsWith("V:")) {
			uri = uri.substring(2);
		}
		if (!uri.startsWith("/~")) {
			return uri;
		}
		String loc = null;
		int idx = uri.indexOf("/", 2);
		if (idx > 0) {
			loc = uri.substring(idx);
		} else {
			loc = "/";
		}
		return loc;
	}
}
